#coding:utf-8
'''
create on 2017-04-20
@author:sandy
'''
import logging
from pycommon import Const
from pycommon import Pack as packet
from pycommon import Utils
import ClientFactory
import ClientBuild
import LogDb

def cmdLogin(client,pkt):
    sid = packet.unpack("H",pkt)
    oldClient = ClientFactory.instance.getClientSrvBySid(sid)
    if oldClient == None:
        logging.debug(u'sid=%d register sucess',sid)
        client.sendPacket(ClientBuild.loginLogServer(Const.ERR_OK))
        client.onLogin(sid)
    else:
        logging.debug(u'sid=%d register Failed,server is exist',sid)
        client.sendPacket(ClientBuild.loginLogServer(Const.ERR_SERVER_EXIST))
    pass

def cmdSaveData(client,pkt):
    uid,msgtype,msg = packet.unpack("IHS",pkt)
    logging.debug(u"sid=%d uid=%d msgtype=%d msg=%s",client.getSId(),uid,msgtype,Utils.pstr2u(msg))
    LogDb.instance.saveMsg(uid,msgtype,Utils.pstr2u(msg))
    pass


__cmdTable = {
        Const.CMD_XX2LOG_LOGIN       : cmdLogin,
        Const.CMD_XX2LOG_SAVE_DATA   : cmdSaveData
    }

def parse(client,cmd,pkt):
    logging.debug(u"ClientParse cmd = %d",cmd)
    func = __cmdTable.get(cmd)
    if not func:
        logging.error("cmd = %d not found",cmd);
    func(client,pkt)

if __name__ == "__main__":
    pass